import Base from "../base.js";
import theatersService from "../../service/theatersService.js";

export default class extends Base {

  constructor(props) {
    super(props);
  }

  render() {
    const template = `
    <form class="layui-form" action="">
    <div class="layui-form-item">
      <label class="layui-form-label">影院</label>
      <div class="layui-input-inline">
        <select name="cinemasId" lay-verify="required">

        </select>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">影厅</label>
      <div class="layui-input-inline addTheaters" style="width:300px">
        <input type="text" name="name"  placeholder="请输入影厅名" class="layui-input layui-input-inline">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">影厅状态</label>
      <div class="layui-input-block">
        <input type="radio" name="status" value=true title="营业" checked>
        <input type="radio" name="status" value=false title="未营业">
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn " lay-submit lay-filter="formDemo" type="button">保存</button>
        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
      </div>
    </div>
  </form>
        `
    this.$el.html(template);
    
  };
  layui(){
    this.form.render()
  };
  //获取影院并渲染到下拉列表方法
  async getCinemas(){
    const data=await theatersService.getCinemas();//向服务器请求影院数据
    this.cinemasRender(data);
  };
//把请求的影院数据渲染到页面的方法
  cinemasRender(data){
    const initOption=`<option value="">请选择影院</option>`;
    const option=data.reduce(
      (accumulator,i)=>
      `${accumulator}<option value="${i._id}">${i.name}<option>`,initOption
  );
  $(`select[name=cinemasId]`).html(option);
        this.form.render();
  };
  async addSeats(data){
    await theatersService.addSeats(data);//向服务器发送请求

  };
  //添加影厅成功后添加座位
  async addTheater(data){
      const result= await theatersService.addTheater(data);//向服务器发送请求
    if (result) {
      layui.layer.msg('添加成功');
      let seats=[];
      for (let i = 1; i <= 9; i++) {//生成座位
        for (let j = 1; j <= 9; j++) {
          const seat = {
            row:i,
            col:j,
            theaterId:result._id,
            status:0
          }
          seats.push(seat);
        }
      }
    await this.addSeats(seats);
    }
    else{
      layui.layer.msg('该影院已存在该影厅');
    }
  };
  handle(){
    var that=this;
    //保存按钮点击事件
    this.form.on('submit(formDemo)', function(data){
      that.addTheater(data.field)//调用addTheater方法
      return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });


  }
  mounted(){
    this.getCinemas()//调用获取影院并渲染到下拉列表方法
  }
}